<template>
  <div>
    <p>{{ typedMessage }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      typedMessage: ''
    };
  },
  mounted() {
    this.startListening();
  },
  methods: {
    startListening() {
      if (typeof(EventSource) !== "undefined") {
        const eventSource = new EventSource("http://localhost:8080");
        eventSource.onmessage = (event) => {
          this.typedMessage += event.data;
        };
        eventSource.onerror = (error) => {
          console.error('EventSource failed:', error);
          eventSource.close();
        };
      } else {
        console.error('Your browser does not support Server-Sent Events.');
      }
    }
  },
  beforeDestroy() {
    // 清理 EventSource 以防内存泄漏
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
}
</script>
